package com.toommi.refuse.controller;

import com.toommi.refuse.annotation.PermissionController;
import com.toommi.refuse.annotation.PermissionReport;
import com.toommi.refuse.common.response.CommonResponse;
import com.toommi.refuse.entity.RecycleRecord;
import com.toommi.refuse.exception.RecycleRecordException;
import com.toommi.refuse.service.AppUserPayStatisticsService;
import com.toommi.refuse.service.AppUserSubStatisticsService;
import com.toommi.refuse.service.RecycleRecordService;
import com.toommi.refuse.service.RecycleStatisticsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * ..
 * 回收记录/垃圾投放记录操作
 *
 * @author yangg
 * @since 2019-08-01 15:51
 */
@RestController(value = "")
@Slf4j
@AllArgsConstructor
@PermissionController(groupCode = "admin_recycle_record", groupName = "回收记录")
@Api(tags = "垃圾同方记录、可回收物回收记录、大件垃圾回收记录")
public class RecycleRecordController {

    private RecycleRecordService recycleRecordService;

    private RecycleStatisticsService statisticsService;

    private AppUserPayStatisticsService appUserPayStatisticsService;

    private AppUserSubStatisticsService subStatisticsService;


    /**
     * 新增垃圾投放/回收记录
     *
     * @param
     * @return 新增结果
     */
//    @ApiOperation(value = "新增垃圾回收记录", notes = "新增垃圾回收记录")
//    @ApiImplicitParam(name = "recycleRecord", value = "回收记录详情", required = true, dataType = "RecycleRecord")
    @PostMapping(value = "/api/recycle/record")
    public CommonResponse addRecycleRecord(HttpServletRequest request, MultipartFile filerefuse, MultipartFile openfile) {
         String refuseType=request.getParameter("refuseType");
        String subRefuseTypeId=request.getParameter("subRefuseTypeId");
        String weight=request.getParameter("weight");
        String price=request.getParameter("price");
        String money=request.getParameter("money");
        String qrcode=request.getParameter("qrcode");
        String appUserId=request.getParameter("appUserId");
        //支付状态
        String PayStatus=request.getParameter("PayStatus");
        String sup_refuse_type_id=request.getParameter("sup_refuse_type_id");
        log.info("打印出是否有图片----------"+filerefuse+"============="+openfile);
        CommonResponse commonResponse = CommonResponse.success();
        RecycleRecord record=new RecycleRecord();
        try {
            record.setQrcode(qrcode);
            record.setRefuseType(refuseType);
            record.setSubRefuseTypeId(Long.valueOf(subRefuseTypeId));
            record.setWeight(Double.valueOf(weight));
            record.setPrice(new BigDecimal(price));
            record.setMoney(new BigDecimal(money));
            if(StringUtils.isNotBlank(appUserId)){
                record.setAppUserId(Long.valueOf(appUserId));
            }

            if(StringUtils.isNotBlank(PayStatus)){
                record.setPayStatus(Integer.valueOf(PayStatus));
            }
            if(StringUtils.isNotBlank(sup_refuse_type_id)){
                record.setSupRefuseTypeId(sup_refuse_type_id);
            }
            recycleRecordService.addRecycleRecord(record,filerefuse,openfile);
        } catch (RecycleRecordException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("add recycle record error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 分页获取回收记录
     *
     * @param pageNum      页码
     * @param pageSize     每页数据量
     * @param wechatUserId 微信用户id
     * @param appUserId    app端处理用户
     * @param householdId  门牌号id
     * @param startTime    查询开始时间
     * @param endTime      结束时间
     * @param status       记录状态
     * @param refuseType   回收大类类型code
     * @return 回收记录列表
     */
    @ApiOperation(value = "查询垃圾回收记录", notes = "查询垃圾回收记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = false, dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数量", required = false, dataType = "int"),
            @ApiImplicitParam(name = "wechatUserId", value = "投放用户id", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "appUserId", value = "操作员id", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "householdId", value = "小区id", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "记录状态（正确/错误/待判断）", required = false, dataType = "int"),
            @ApiImplicitParam(name = "refuseType", value = "回收类型(普通、可回收、大件)", required = false, dataType = "String")
    })
    @GetMapping(value = "/api/recycle/records", produces = "application/json;charset=UTF-8")
    public CommonResponse findRecycleRecords(@RequestParam(required = false, defaultValue = "1") int pageNum,
                                             @RequestParam(required = false, defaultValue = "10") int pageSize,
                                             @RequestParam(required = false, defaultValue = "-1") long wechatUserId,
                                             @RequestParam(required = false, defaultValue = "-1") long appUserId,
                                             @RequestParam(required = false, defaultValue = "-1") long householdId,
                                             @RequestParam(required = false, defaultValue = "-1") long startTime,
                                             @RequestParam(required = false, defaultValue = "-1") long endTime,
                                             @RequestParam(required = false, defaultValue = "-1") int status,
                                             @RequestParam(required = false, defaultValue = "") String refuseType) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(recycleRecordService.findRecycleRecords(pageNum, pageSize, wechatUserId, appUserId,
                    householdId, startTime, endTime, status, refuseType));
        } catch (Exception e) {
            log.error("find recycle records error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;

    }

    /**
     * 查询详情
     *
     * @param id 记录id
     * @return 记录详情
     */
    @ApiOperation(value = "获取垃圾回收记录详情", notes = "获取垃圾回收记录详情")
    @ApiImplicitParam(name = "id", value = "回收记录详情id", required = true, dataType = "Long")
    @GetMapping(value = "/api/recycle/record/{id}", produces = "application/json;charset=UTF-8")
    public CommonResponse findDetail(@PathVariable(name = "id") long id) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(recycleRecordService.findDetail(id));
        } catch (Exception e) {
            log.error("find recycle record detail error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 管理端更新正确性判断状态
     *
     * @param record 记录信息
     * @return 更新结果
     */
    @ApiOperation(value = "管理端更新正确性判断", notes = "管理端更新正确性判断")
    @ApiImplicitParam(name = "recycleRecord", value = "回收记录详情", required = true, dataType = "RecycleRecord")
    @RequiresPermissions("admin:recycle:record:update")
    @PermissionReport(value = "admin:recycle:record:update", name = "审核正确性", group = "admin_recycle_record")
    @PutMapping(value = "/admin/recycle/record", produces = "application/json;charset=UTF-8")
    public CommonResponse updateRecycleRecordAdmin(@RequestBody RecycleRecord record) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            recycleRecordService.updateRecycleRecord(record);
        } catch (RecycleRecordException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        }
        return commonResponse;
    }

    /**
     * APP端更新支付状态
     *
     * @param record 记录
     * @return 更新结果
     */
    @ApiOperation(value = "App端更新支付状态", notes = "App端更新支付状态")
    @ApiImplicitParam(name = "recycleRecord", value = "回收记录详情", required = true, dataType = "RecycleRecord")
    @PutMapping(value = "/api/recycle/record", produces = "application/json;charset=UTF-8")
    public CommonResponse updateRecycleRecordApi(@RequestBody RecycleRecord record) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            recycleRecordService.updateRecycleRecord(record);
        } catch (RecycleRecordException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        }
        return commonResponse;
    }

    /**
     * 获取用户总收益信息
     *
     * @param wechatUserId 用户信息
     * @return 用户总收益
     */
    @ApiOperation(value = "获取用户总收益信息", notes = "获取用户总收益信息")
    @ApiImplicitParam(name = "wechatUserId", value = "用户id", required = true, dataType = "Long")
    @GetMapping(value = "/api/recycle/benefit/total", produces = "application/json;charset=UTF-8")
    public CommonResponse totalBenefit(String wechatUserId) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(statisticsService.totalBenefit(wechatUserId));
        } catch (RecycleRecordException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("find total benefit error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 根据回收类型，及月份查询收益统计
     *
     * @param refuseType   回收类型
     * @param date         月份日期
     * @param wechatUserId 用户id
     * @return 收益信息
     */
    @ApiOperation(value = "根据回收类型、月份查询用户收益统计", notes = "根据回收类型、月份查询用户收益统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refuseType", value = "回收类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "date", value = "回收时间，格式为yyyy-mm", required = true, dataType = "date"),
            @ApiImplicitParam(name = "wechatUserId", value = "用户id", required = true, dataType = "wechatUserId")
    })
    @GetMapping(value = "/api/recycle/benefit/date", produces = "application/json;charset=UTF-8")
    public CommonResponse dateBenefit(String refuseType, String date, long wechatUserId) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(statisticsService.countBenefit(refuseType, date, wechatUserId));
        } catch (RecycleRecordException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("find date benefit error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 计算正确率
     *
     * @param wechatUserId 微信用户
     * @param startTime    开始时间
     * @param endTime      结束时间
     * @return 正确率
     */
    @ApiOperation(value = "计算用户投放正确率", notes = "计算用户投放正确率")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "统计开始时间，时间戳", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "endTime", value = "统计结束时间，时间戳", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "wechatUserId", value = "用户id", required = true, dataType = "Long")
    })
    @GetMapping(value = "/api/recycle/ratio", produces = "application/json;charset=UTF-8")
    public CommonResponse correctRatio(long wechatUserId, long startTime, long endTime) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(recycleRecordService.getCorrectRatio(wechatUserId, startTime, endTime));
        } catch (Exception e) {
            log.error("get correct ratio error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 计算APP端用户支付统计
     *
     * @param appUserId  app用户
     * @param date       日期时间
     * @param refuseType 回收类型
     * @return 支付数据
     */
    @ApiOperation(value = "计算APP端用户支付统计", notes = "计算APP端用户支付统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "统计开始时间，时间戳", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "endTime", value = "统计结束时间，时间戳", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "wechatUserId", value = "用户id", required = true, dataType = "Long")
    })
    @GetMapping(value = "/api/recycle/pay/statistics", produces = "application/json;charset=UTF-8")
    public CommonResponse appUserPayStatistics(long appUserId, String date, String refuseType) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(appUserPayStatisticsService.getStatistics(appUserId, date, refuseType));
        } catch (Exception e) {
            log.error("get app user pay statistics error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 获取APP用户当天的回收记录重量统计--包含各子类
     *
     * @param appUserId app用户
     * @param date      日期
     * @return 重量信息
     */
    @ApiOperation(value = "获取App用户当天各子类回收记录重量统计", notes = "获取App用户当天各子类回收记录重量统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appUserId", value = "App用户id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "date", value = "日期时间，格式为 yyyy-mm-dd", required = true, dataType = "String")
    })
    @GetMapping(value = "/api/recycle/weight/statistics/day", produces = "application/json;charset=UTF-8")
    public CommonResponse appUserWeightStatistics(long appUserId, String date) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(subStatisticsService.getStatistics(appUserId, date));
        } catch (Exception e) {
            log.error("get app user weight statistics error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 获取APP用户在每个月的统计详情
     *
     * @param appUserId APP用户id
     * @param date      月份时间 格式为 yyyy-mm 如 2019-08
     * @return 该月份统计详情，包含每一天的重量
     */
    @ApiOperation(value = "获取App用户每个月回收记录重量统计", notes = "获取App用户每个月回收记录重量统计，返回该月每天的统计信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appUserId", value = "App用户id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "date", value = "日期时间，格式为 yyyy-mm", required = true, dataType = "String")
    })
    @GetMapping(value = "/api/recycle/weight/statistics/month", produces = "application/json;charset=UTF-8")
    public CommonResponse appUserWeightMonth(long appUserId, String date) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(subStatisticsService.getMonthStatistics(appUserId, date));
        } catch (Exception e) {
            log.error("get app user weight statistics month error:{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }
}
